//
//  CCSaoMaVC.swift
//  swift_weibo
//
//  Created by ccl on 16/3/9.
//  Copyright © 2016年 LittleBoy. All rights reserved.
//


import UIKit
import AVFoundation


///  扫描view的代理
protocol saomaViewDelegate: NSObjectProtocol{
    // 点击生成我的二维码时调用
    func saomaViewCreatMyCodeBtnDidClick(sender: UIButton);
}

class CCSaoMaVC: UIViewController,saomaViewDelegate {
    
    var saomaV: saomaView?
   // 扫描view替换 系统view
    override func loadView() {
        super.loadView();
        saomaV  = saomaView.creatSaomaView() ;
        saomaV?.saomaDelegate = self;
        view = saomaV;
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
      creatNavBar()
        self.title = "扫一扫";
        // 添加session
        saomaV?.creatAddSession();
        saomaV?.setupLayers();
    }
    // 设置导航栏
    func creatNavBar(){
        let leftBtn = UIButton();
        leftBtn.setTitle("关闭", forState: UIControlState.Normal);
        leftBtn.addTarget(self, action: "leftNavBtnDidClick:", forControlEvents: UIControlEvents.TouchUpInside);
        leftBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal);
        leftBtn.frame.size = CGSizeMake(50, 30);
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn);
    }
    
    func leftNavBtnDidClick(sender:UIButton){
    
        self.dismissViewControllerAnimated(true, completion: nil);
    }
   
  //开启二维码动画
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated);
        // 开始动画
        saomaV?.creatAnimation();
        //开始扫描
        saomaV?.startSaoMa();
    }
  
   // 扫描view代理
    func saomaViewCreatMyCodeBtnDidClick(sender: UIButton) {
        navigationController?.pushViewController(CCMyCode(), animated: true);
    }
}

// MARK: saomaview 从xib中加载
class saomaView: UIView , AVCaptureMetadataOutputObjectsDelegate{
   
    weak var saomaDelegate: saomaViewDelegate?;
    
    // 冲击波 top 约束
   // @IBOutlet weak var chongjibuoTopConstrain: NSLayoutConstraint!
    @IBOutlet weak var chongjibuoTopConstrain: NSLayoutConstraint!
    // 底部tabBar
    @IBOutlet weak var CCSaoMaTabBar: UITabBar!
    
    // 扫描框
    @IBOutlet weak var saomiaoKuang: UIImageView!
   
    // 容器视图高的约束
    @IBOutlet weak var contentViewH: NSLayoutConstraint!
    class func creatSaomaView()->saomaView{
        let saomaViewAry  = NSBundle.mainBundle().loadNibNamed("CCsaoMa", owner: nil , options: nil) as NSArray;
        return saomaViewAry.lastObject! as! saomaView;
    }
    
    // 点击按钮生成我的二维码
    @IBAction func creatMyCode(sender: AnyObject) {
        saomaDelegate?.saomaViewCreatMyCodeBtnDidClick(sender as! UIButton);
    }
    
///  开启冲击波动画
    func creatAnimation(){
        chongjibuoTopConstrain.constant = -contentViewH.constant;
        self.layoutIfNeeded();
        
        UIView.animateWithDuration(2.0, animations: { () -> Void in
            // 设置循环次数
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.chongjibuoTopConstrain.constant = self.contentViewH.constant;
            self.layoutIfNeeded();
        })
    }
    
    // 设置预览图层
     func setupLayers(){
        //设置绘画线图层
        drawLayer.frame = self.bounds;
        
        self.layer.insertSublayer(drawLayer, atIndex: 0);
        
        
        // 设置图层大小
        previewLayer.frame = self.bounds;
        // 设置图层填充模式 据说不设置, 4s 会有影响  设置的是填充模式
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        //现将drawLayer 放置最下层, 在将previewLayer 放置最下层.  现在previewLayer在最下层
        self.layer.insertSublayer(previewLayer, atIndex: 0);
        
    
    }
    // 将输入设备, 输出设备添加到 session中
     func creatAddSession(){
        if !session.canAddInput(inputDevice){
            // 输入设备添加失败
            return;
        }
    
        if !session.canAddOutput(outPutData){
           // 输出设备添加失败
            return;
        }
        
        // 检测完毕, 开始添加
        session.addInput(inputDevice);
        session.addOutput(outPutData);
        
        // 设置 元数据 检测数据的类型
        outPutData.metadataObjectTypes = outPutData.availableMetadataObjectTypes;
        
        // 设置代理
        outPutData.setMetadataObjectsDelegate(self, queue:dispatch_get_main_queue());
    }
    // 开始扫描
    func startSaoMa(){
    
        session.startRunning();
    }
    
    // MARK: 扫描代理
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
        // 先清除绘画层画的线.
        creatClearLine();
        
        for objects in metadataObjects{
        if objects is AVMetadataMachineReadableCodeObject{
          
            // 转换数据类型 不懂的是为什么要用预览图层调起
             let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(objects as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
//            
            creatDrawLayer(codeObject);
        }
      }
    }
    // 绘制绿色线
    private func creatDrawLayer(cornersObj: AVMetadataMachineReadableCodeObject){
    
        let lineLayer = CAShapeLayer();
        // 线宽4
        lineLayer.lineWidth = 4;
        // 线的颜色
        lineLayer.strokeColor = UIColor.greenColor().CGColor;
        // 内部的填充颜色
        lineLayer.fillColor = UIColor.clearColor().CGColor;
        
        lineLayer.path = creatLineLayerPath(cornersObj.corners).CGPath;
        drawLayer.addSublayer(lineLayer);
    }
    // 穿件划线 贝塞尔曲线
    private func creatLineLayerPath(corners:NSArray)->UIBezierPath{
    
        let path = UIBezierPath();
        
        var point = CGPoint();
        var index = 0;
        
        CGPointMakeWithDictionaryRepresentation(corners[index] as! CFDictionary, &point)
        path.moveToPoint(point);
        index++;
        
        while index < corners.count{
        CGPointMakeWithDictionaryRepresentation(corners[index] as! CFDictionary, &point)
            path.addLineToPoint(point);
            index++;
        }
        
        // 关闭
        path.closePath();
        return path;
    }
    
    private func creatClearLine(){
        if drawLayer.sublayers == nil{
        
            return;
        }
        for subLayer in drawLayer.sublayers!{
        
            subLayer.removeFromSuperlayer();
        }
    
    }
    // MARK: 懒加载
    // 绘制线的图层
    lazy var drawLayer:CALayer = {
        return CALayer();
    }()
    //预览图层
    lazy var previewLayer:AVCaptureVideoPreviewLayer = {
    
       return AVCaptureVideoPreviewLayer(session: self.session);
    }()
    
    // 扫描会话
    lazy var session:AVCaptureSession = AVCaptureSession()

    // 输入设备
    lazy var inputDevice:AVCaptureDeviceInput? = {
      
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo);
        do{
        return  try AVCaptureDeviceInput(device: device)
        }catch{
            print(__FUNCTION__ + "\(error)");
            return nil;
        }
    
    }()
    // 输出设备
    lazy var outPutData: AVCaptureMetadataOutput = {
        return AVCaptureMetadataOutput();
    }()
    
}
